package proxyHandler;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;

import annotations.AsCommand;
import logging.confLogger;

public class OwnHandler implements InvocationHandler {

	private Object object;
	private static Logger log = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

	public OwnHandler(Object object) throws IOException {
		this.object = object;
		confLogger.setup();
		log.setLevel(Level.FINE);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		AsCommand ascommandAnnotation = method.getAnnotation(AsCommand.class);
		StringBuilder argumentsToString = new StringBuilder();
		for (int i = 0; i < args.length; i++) {
			argumentsToString.append(args[i].toString() + " ");
		}

		log.log(Level.INFO,
				"MethodName: " + method.getName()
						+ "  ---  whole command with arguments: "
						+ ascommandAnnotation.commandShellCommando() + " "
						+ argumentsToString.toString());
		/**
		 * give this handler to command
		 */

		Object result = null;
		try {
			result = method.invoke(object, args);

		} catch (InvocationTargetException e) {
			log.log(Level.SEVERE, e.getCause().toString());
			throw e.getCause();
		}

		return null;
	}

}
